import { login, logout } from '@/api/login'
import { setToken, getToken, removeToken } from '@/utils/mUtils'

const user = {
  // state就是Vuex中的公共的状态, 我是将state看作是所有组件的data, 用于保存所有组件的公共数据.
  state: {
    token: getToken()
  },
  mutations: {
    SET_TOKEN: (state, token) => {
      state.token = token
      setToken(token)
    }
  },
  actions: {
    // 登入
    Login: (context, userInfo) => {
      return new Promise((resolve, reject) => {
        login(userInfo)
          .then(response => {
            let token = response.token
            context.commit('SET_TOKEN', token)
            setToken(token)
            resolve(response)
          })
          .catch(error => {
            reject(error + 'kk')
          })
      })
    },
    // 登出
    logOut: (context, state) => {
      return new Promise((resolve, reject) => {
        logout(state.token)
          .then(() => {
            context.commit('SET_TOKEN', '')
            removeToken()
            resolve()
          })
          .catch(error => {
            reject(error)
          })
      })
    },
    // 前端登出
    FedlogOut: context => {
      return new Promise(resolve => {
        context.commit('SET_TOKEN', '')
        removeToken()
        resolve()
      })
    }
  }
}

export default user
